import { login, logout, getInfo, getMenus } from '@/api/login'
import { getToken, setToken, removeToken, setUid,getUid,removeUid ,switchHost, removeKey} from '@/utils/auth'

const user = {
  state: {
    token: getToken(),
    name: '',
    avatar: '',
    roles: [],
    uid: getUid(),
    transmit:{},
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = switchHost(avatar)
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_UID: (state,uid)=> {
      state.uid = uid
    }
  },

  actions: {
    // 登录
    Login({ commit }, userInfo) {
      const phoneNumber = userInfo.phoneNumber.trim()
      const phoneCode = userInfo.code.trim()
      const loginType = userInfo.loginType.trim()
      let data = {}
      if (loginType === "phone") {
        data = { phoneCode,phoneNumber }
      } else {
        const username = userInfo.username.trim()
        const password = userInfo.password.trim()
        data = { username,password }
      }
      return new Promise((resolve, reject) => {
        login(data,loginType).then(response => {
          const data = response.data
          const tokenStr = data.tokenHead+ ' ' + data.token
          const uid = data.userId
          setToken(tokenStr)
          commit('SET_TOKEN', tokenStr)
          setUid(uid)
          commit('SET_UID', uid)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 获取用户信息
    GetInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        getInfo().then(response => {
          const data = response.data
          if (data.roles && data.roles.length > 0) { // 验证返回的roles是否是一个非空数组
            commit('SET_ROLES', data.roles)
          } else {

            reject('用户没有配置相关角色')
          }
          commit('SET_NAME', data.username)

          commit('SET_AVATAR', data.icon ? data.icon : '')
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },



    // 获取用户菜单
    GetMenus({ commit, state }) {
      return new Promise((resolve, reject) => {
        getMenus().then(response => {
          resolve(response)
        }).catch(error => {
          // reject(error)
        })
      })
    },

    // 登出
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout(state.token).then(() => {
          commit('SET_TOKEN', '')
          commit('SET_ROLES', [])
          removeToken()
          commit('SET_UID', '')
          removeUid()
          resolve()
          removeKey()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        removeToken()
        resolve()
      })
    }
  }
}

export default user
